<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <input type="text" placeholder="请输入聊天内容">
    <button class="btn1"> 点我发送</button>
    <button class="btn2"> 关闭聊天</button>
    <br>
    <div class="container"></div>
</head>

<body>
    <script>
        let container = document.querySelector('.container')
        //1.创建websocket链接 (链接服务器)

        //wss://echo.websocket.org  你给服务器发什么 ,服务器就返回什么
        let ws = new WebSocket('wss://echo.websocket.org')

        //2.注册链接成功回调
        ws.onopen = function () {
            container.innerHTML += '<p style="color:red">链接服务器成功</p>'
        }
        //3.主动给服务器发数据
        document.querySelector('.btn1').onclick = function () {
            let str = document.querySelector('input').value
            container.innerHTML += `<P>用户:${str}</p>`
            //发送信息
            ws.send(str)
        }
        //4.接收服务器数据
        ws.onmessage = function (data) {
            console.log(data);
            container.innerHTML += `<p>服务器:${data.data}</p>`
        }
        //5关闭链接
        document.querySelector('.btn2').onclick = function () {
            ws.close()
        }
        //6.关闭成功事件
        ws.onclose = function () {
            container.innerHTML += '<p style="color:red">关闭服务器成功</p>'
        }
    </script>
</body>

</html>